# -*- coding: utf8 -*-
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* skip_sentinel: skip sentinel instance
* limit
* channels
* url
"""

import json, os, re, time
from util.functions import *
from core.ircfuncs import quiet_nick
from util.pywikilib import Time, Site
field = "lists"

_sites = {}
def send_lists(bot, evt, cmd):
    stack=cmd.command
    list_name=""
    if stack=="llista" or stack=="cua":
       stack=bot.logs.usersQueue
       list_name="de voluntaris disponibles en cua"
    elif stack=="connectats":
       list_name="d'usuaris connectats"
       stack=bot.channels[evt.chan].users()
    elif stack=="interessats":
       list_name="d'usuaris %s per ser avisats"%stack
       stack=bot.logs.interested
    elif stack=="operadors":
       list_name=u"d'%s" % stack
       stack=bot.channels[evt.chan].opers()
    elif stack=="moderadors":
       list_name="de %s" % stack
       stack=bot.channels[evt.chan].voiced()
    elif stack=="autoritzats":
       list_name="d'%s" % stack
       stack=bot.logs.logs['authorized']
    elif stack=="admins":
        site = Site(evt.lang, evt.fam)
        if not _sites.has_key(site.sitename()):
           site.load_users()
           _sites[site.sitename()] = {'sysops': site._users_tuple[0]}
        list_name="d'%s"%stack
        stack=[]
        for usr in bot.channels[evt.chan].users():
            nickVP=bot.accounts.get(bot.nicks.get(usr), {"wiki":None})['wiki']
            if nickVP in _sites[site.sitename()]['sysops']:
                if nickVP != usr:
                    usr = u"%s &N;(VP: &e;%s&N;)" % (quiet_nick(usr, bot.channels[evt.chan].users()), nickVP)
                else:
                    usr = quiet_nick(usr, bot.channels[evt.chan].users())
                stack.append(usr)
    if list_name:
        bot.reply(evt, "%s list: %s.", list_name, join_userlist(stack, bot.channels[evt.chan].users(), evt.lang))
send_lists.rule=re.compile(r"^(connectats|llista|cua|operadors|moderadors|interessats|autoritzats|admins)$")
send_lists.showas = "connectats, llista, operadors, moderadors, interesats, autoritzats, admins"

def modify_list(bot, evt, cmd):
    if cmd.arguments == 'auth':
        list_ = bot.logs['authorized']
        if cmd.opt['r']:
            if params['r'] in list_:
               list_.remove(params['r'])
            else:
                bot.reply(evt, "%s no és a la llista" % params['r'])
                return True
        if cmd.opts['add']:
            list_.append(params['add'])
        bot.pubmsg("S'han efectuats els canvis.")
        bot.logs['authorized']=list_
        bot.logs.save()
modify_list.rule = "list"

def aliases(bot, user):
    acc = bot.nicks[user]
    for alias in bot.accounts[acc]['aliases']:
        if alias in bot.channels[bot.event.chan].users():
            return alias
    return user

def remove_usr(bot, evt, cmd):
    #traem l'usuari si es trau ell mateix, o si qui ho fa és un moderador
    req_usr = cmd.dict['nick'] or evt.source
    usr=aliases(bot, req_usr)
    if usr in bot.channels[evt.chan].users():
       if ((evt.source == usr) or (evt.source != usr and evt.identified)):
           if usr in bot.logs.usersQueue:
              bot.logs.usersQueue.remove(usr)
              bot.logs.save()
              usersQueue_str=bot.list_users(bot.logs.usersQueue)
              bot.reply(evt, "s'ha eliminat l'usuari de la cua.")
              bot.reply(evt, "llista de voluntaris disponibles en cua: %s." % usersQueue_str)
              if len(bot.logs.usersQueue)==0 and len(bot.channels[evt.chan].users())>0:
                  callUsers = list(bot.channels[evt.chan].users())
                  callUsers.remove(usr)
                  list_ = bot.list_users(callUsers)
                  list_ = "%s. " % list_ if  "(buida)" not in list_ else ""
                  list_ = list_.replace(u"·","")
                  qui = u"Algú vol " if len(callUsers)>1 else "Vols"
                  msg = u"%sLa llista és buida. %s entrar-hi?" % (list_, qui)
                  bot.replace(msg)
           else:
              bot.reply(evt, "l'usuari no figura a la llista.")
       else:
          bot.reply(evt, "No teniu els permissos necessaris.")
    else:
          bot.reply(evt, "L'usuari no existeix o no està present en estos moments.")
remove_usr.rule = re.compile(r'^(?P<cmd>tr[ae]u|-)(?P<nick>[^ ]+)?$')

def add_usr(bot, evt, cmd):
    #afegix un usuari a la cua
    req_usr = cur.params or evt.source
    usr=aliases(req_usr)
    if usr in bot.channels[evt.chan].users():
        if usr not in bot.logs.usersQueue:
            if ((evt.source == usr) or (evt.source != usr and cur.identifiedUser)):
               bot.logs.usersQueue.insert(0, usr)
               bot.save_log()
               usersQueue_str=bot.list_users(bot.logs.usersQueue)
               bot.pubmsg("s'ha afegit l'usuari a la cua.")
               bot.pubmsg("llista de voluntaris disponibles en cua: %s." % encode_msg(usersQueue_str))
            else:
               bot.pubmsg("No teniu els permissos necessaris.")
        else:
           bot.pubmsg("Ja consta aquest usuari a la llista")
    else:
        bot.pubmsg("L'usuari no existeix o no està present en estos moments.")
add_usr.rule = re.compile(r'^(?:both)afege?ix|^\.\+$')
add_usr.showas = "afegeix"

def change_queue_(bot, evt, cmd):
   #passem l'usuari a la posició desitjada de la cua, sols per moderadors, que algun privilegi han de tenir
   if re.search(ur"^-?[1-9][0-9]*$",cmd) and identifiedUser:
      ordinal=int(cmd)
      if ordinal<0:
         ordinal=len(bot.logs.usersQueue)-abs(ordinal)
      else:
         ordinal-=1
      req_usr = cur.params or evt.source
      usr=aliases(req_usr)
      if usr in bot.channels[evt.chan].users():
         if usr == evt.source or (usr != evt.source and identifiedUser):
            if usr in bot.logs.usersQueue:
               cuaUsuarisAbans = bot.logs.usersQueue
               bot.logs.usersQueue.remove(usr)
               bot.logs.usersQueue.insert(ordinal, usr)
               bot.save_log()
               usersQueue_str=bot.list_users(bot.logs.usersQueue)
               if cuaUsuarisAbans != bot.logs.usersQueue:
                  bot.pubmsg("s'ha modificat l'ordre de la cua.")
                  bot.pubmsg("llista de voluntaris disponibles en cua: %s."%usersQueue_str.encode('utf-8'))
               elif usr not in bot.logs.usersQueue:
                  bot.logs.usersQueue.insert(ordinal, usr)
                  bot.save_log()
                  usersQueue_str=bot.list_users(bot.logs.usersQueue)
                  bot.pubmsg("s'ha afegit l'usuari a la cua en l'ordre indicat.")
                  bot.pubmsg("llista de voluntaris disponibles en cua: %s." % usersQueue_str.encode('utf-8'))
               else:
                  bot.pubmsg(u"no teniu els permissos suficients per efectuar este canvi".encode('utf-8'))
      else:
         bot.pubmsg(u"l'usuari no està present o no existeix".encode('utf-8'))
change_queue_.load = False

def nocmd_addUsr_(bot, evt, cmd):
   add_usr(bot, evt, cmd)
nocmd_addUsr_.rule = re.compile(r"^(?:entr[eo]|present)[!.]?$")
nocmd_addUsr_.fullmsg = True

def nocmd_remUsr_(bot, evt, cmd):
   remove_usr(bot, evt, cmd)
nocmd_remUsr_.rule = re.compile(r"^(?:isc|(?:me'n|m'en) vaig|surto?|ara torn[eo]?)[!.]?$")
nocmd_remUsr_.fullmsg = True

def ignored(bot, evt, cmd):
    target = cmd.arguments and cmd.arguments.replace("::","")
    if target and bot.ignored.has_key(target):
        print bot.ignored[target]
    elif target and not bot.ignored.has_key(target):
        bot.reply(evt, "no match for user")
    else:
        if len(bot.ignored)==0:
            bot.reply(evt, "no user ignored")
            return
        for ign in bot.ignored:
            bot.ctrl_msg(evt,
                "%s: from %s till %s" % (
                    ign,
                    Time(bot.ignored[ign][0]).to_simple_string(),
                    Time(bot.ignored[ign][0]+bot.ignored[ign][1]).to_hour_string()
                )
            )
ignored.rule = "ign"

def requests(bot, evt, cmd):
    bot.reply(evt,
        " | ".join(
            ["&B;%s:&N; %s" % (
                quiet_nick(req, bot.channels[evt.chan].users()),
                ", ".join(
                    ["&l;%s&N;: %s &t;%i&N; times" % (
                        cmd,
                        Time(bot._requests[req][cmd][0]).to_string(),
                        bot._requests[req][cmd][1]) for cmd in bot._requests[req]])) for req in bot._requests]
            )
        )
requests.rule = "queries"
requests.aliases = ["requests", "req"]
